import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:silver_flutter/api.dart' as api;
import 'package:silver_flutter/event/user_events.dart';
import 'package:silver_flutter/login_page.dart';
import 'package:silver_flutter/event_bus.dart';

class FavButton extends StatefulWidget {
  final int bookId;

  FavButton({Key key, this.bookId}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new _FavButtonState();
  }
}

class _FavButtonState extends State<FavButton> {
  StreamSubscription _loginSub;
  bool _isLoggedIn = api.isLoggedIn();
  bool _isFavourite = false;

  @override
  void dispose() {
    _loginSub.cancel();

    super.dispose();
  }

  @override
  void initState() {
    super.initState();

    _loginSub = eventBus.on(UserLoggedInEvent).listen((event) {
      setState(() {
        _isLoggedIn = true;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoggedIn) {
      return new FutureBuilder<bool>(
          future: api.fetchFavourite(widget.bookId),
          builder: (context, snapshot) {
            _isFavourite = snapshot.hasData && snapshot.data;
            return new IconButton(
                icon: Icon(
                  (snapshot.hasData && snapshot.data)
                      ? Icons.favorite
                      : Icons.favorite_border,
                  color: Colors.white,
                ),
                onPressed: () {
                  if (_isFavourite) {
                    api
                        .removeFromFavourites(widget.bookId)
                        .then((_) => setState(() => _isFavourite = false));
                  } else {
                    api
                        .addToFavourites(widget.bookId)
                        .then((_) => setState(() => _isFavourite = true));
                  }
                });
          });
    } else {
      return new IconButton(
          icon: new Icon(
            Icons.favorite_border,
            color: Colors.white,
          ),
          onPressed: () {
            Navigator.push(
              context,
              new MaterialPageRoute(
                builder: (context) => new LoginPage(),
              ),
            );
          });
    }
  }
}
